package www.sofn.com.sys.roles;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import www.sofn.com.domain.R;
import www.sofn.com.domain.vo.SelectVO;
import www.sofn.com.sys.roles.domain.pojo.SysRolesPO;
import www.sofn.com.sys.roles.domain.query.SysRolesQuery;
import www.sofn.com.sys.roles.domain.vo.ListSysRolesVO;
import www.sofn.com.sys.roles.domain.vo.SysRolesVO;
import www.sofn.com.validate.group.InsertGroup;
import www.sofn.com.validate.group.UpdateGroup;

import java.util.List;

@RestController
@RequestMapping("sys_roles")
@Tag(name = "角色模块")
public class SysRolesController {
    @Autowired
    private SysRolesService sysRolesService;

    @Operation(summary = "查询角色列表")
    @GetMapping
    @PreAuthorize("hasAuthority('sys:roles:select')")
    public R<List<ListSysRolesVO>> pageList(SysRolesQuery query) {
        return R.ok(sysRolesService.list(query));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取角色详情")
    @PreAuthorize("hasAuthority('sys:roles:select')")
    public R<SysRolesVO> getRolesById(@PathVariable(value = "id", required = true) String id) {
        return R.ok(sysRolesService.getById(id));
    }

    @Operation(summary = "新增角色")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:roles:create')")
    public R insert(@RequestBody @Validated(value = {InsertGroup.class}) SysRolesVO sysRolesVO) {
        sysRolesService.save(BeanUtil.toBean(sysRolesVO, SysRolesPO.class), sysRolesVO.getResources());
        return R.ok();
    }

    @Operation(summary = "修改岗位")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:roles:update')")
    public R update(@RequestBody @Validated(value = {UpdateGroup.class}) SysRolesVO sysRolesVO) {
        sysRolesService.update(BeanUtil.toBean(sysRolesVO, SysRolesPO.class), sysRolesVO.getResources());
        return R.ok();
    }

    @Operation(summary = "删除岗位")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:roles:delete')")
    public R delete(@PathVariable(value = "id", required = true) String id) {
        sysRolesService.deleteById(id);
        return R.ok();
    }

    @Operation(summary = "查询角色")
    @GetMapping("/find")
    public R<SelectVO> findRoles() {
        return R.ok(sysRolesService.findRolesPO());
    }
}
